package com.ebt.m.proposal_v2.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;

/**
 * @author archer.qi
 *         Created on 2017/9/25.
 */
public abstract class EBTRecyclerAdapter<T, VH extends EBTRecyclerAdapter.EBTRecyclerViewHolder> extends RecyclerView.Adapter<VH> {
    private Context context;
    private List<T> data;
    private LayoutInflater inflater;

    public EBTRecyclerAdapter(Context context, List<T> data) {
        this.context = context;
        this.data = new ArrayList<>();
        this.data.addAll(data);
        this.inflater = LayoutInflater.from(this.context);
    }

    public void resetData(List<T> data) {
        if (this.data == null) {
            this.data = new ArrayList<>();
            this.data.addAll(data);
        } else {
            this.data.clear();
            this.data.addAll(data);
        }
        notifyDataSetChanged();
    }

    public Context getContext() {
        return context;
    }

    public List<T> getData() {
        return data;
    }

    public LayoutInflater getInflater() {
        return inflater;
    }

    @Override
    public VH onCreateViewHolder(ViewGroup parent, int viewType) {
        return createViewHolder(inflater.inflate(createConvertView(), parent, false));
    }

    @Override
    public void onBindViewHolder(VH holder, int position) {
        T entity = data.get(position);
        if (entity == null) {
            return;
        }
        holder.initViewHolder(entity, position);
    }

    protected abstract VH createViewHolder(View itemView);

    protected abstract int createConvertView();

    @Override
    public int getItemCount() {
        return this.data == null ? 0 : this.data.size();
    }

    public abstract static class EBTRecyclerViewHolder<T> extends RecyclerView.ViewHolder {
        private Context context;
        private T data;
        private int position;

        public EBTRecyclerViewHolder(Context context, View itemView) {
            super(itemView);
            this.context = context;
            ButterKnife.bind(this, itemView);
        }

        protected void initViewHolder(final T data, final int position) {
            this.data = data;
            this.position = position;
            onBindView(itemView, this.data, this.position);
        }

        protected Context getContext() {
            return context;
        }

        protected abstract void onBindView(View itemView, T data, int position);

    }
}
